package scooper.cn.sc_base;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by zhaoboliang  on 2017/1/16.
 */

public class SCFileUtils {
    private static final String TAG = "SCFileUtils";

    /**
     * @param context
     * @return 根据包名获得文件夹路径
     */
    public static String bindAppPacketToPath(Context context) {
        File sdDir = null;

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            sdDir = Environment.getExternalStorageDirectory();
        }

        if (sdDir == null) {
            return null;
        }
        File scooperDir = new File(sdDir + File.separator + "scooper");
        if (!scooperDir.exists()) {
            if (!scooperDir.mkdirs()) {
                return null;
            }
        }

        File appDir = new File(scooperDir + File.separator + context.getPackageName());
        if (!appDir.exists()) {
            if (!appDir.mkdir()) {
                return null;
            }
        }

        return appDir.getAbsolutePath();
    }


    public static boolean createDir(String dstDirPath,String
            dirName){
        File file = new File(dstDirPath, dirName);
        return createDir(file);
    }

    public static boolean createDir(File dirFile) {
        if (!dirFile.exists()) {
            return dirFile.mkdirs();
        } else {
            Log.w(TAG, "dir exits. name " + dirFile.getAbsolutePath());
        }
        return true;
    }

    /**
     * @param dstDirPath 目标文件夹路径
     * @param fileName   文件名
     * @return 返回操作是否成功
     */
    public static boolean createFile(String dstDirPath, String fileName) {
        File file = new File(dstDirPath, fileName);
        if (!file.getParentFile().exists() && !createDir(file.getParentFile())) {
            return false;
        }
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                Log.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } else {
            Log.w(TAG, "file exits. name " + dstDirPath + "/" + fileName);
        }
        return true;
    }

    public static boolean createFile(File file) {
        return createFile(file.getParentFile().getAbsolutePath(), file.getName());
    }

    /**
     * 复制文件
     *
     * @param context    上下文
     * @param srcPath    源文件路径
     * @param dstDirPath 目标 文件夹 路径
     * @param newName    新文件名
     * @param overlay    是否覆盖
     * @return 返回操作是否成功
     */
    public static boolean copyFile(Context context, String srcPath, String
            dstDirPath, String newName, boolean overlay) {

        File srcFile = new File(srcPath);
        if (!srcFile.exists()) {

            Log.e(TAG, "file is not exists. name : " + srcPath);
            return false;
        }

        if (!srcFile.isFile()) {
            Log.e(TAG, "this is a dir. src path : " + srcPath);
            return false;
        }

        // 判断目标文件是否存在
        File destFile = new File(dstDirPath + File.separator + newName);
        if (destFile.exists()) {
            // 如果目标文件存在并允许覆盖
            if (overlay) {
                // 删除已经存在的目标文件，无论目标文件是目录还是单个文件
                Log.i(TAG, "starting delete dst file. path : " + destFile
                        .getAbsolutePath());

                if (destFile.delete()) {
                    Log.i(TAG, "delete dst file success");
                } else {
                    Log.e(TAG, "delete dst file failed. path : " + destFile
                            .getAbsolutePath());
                    return false;
                }
            }
        } else {
            // 如果目标文件所在目录不存在，则创建目录
            if (!destFile.getParentFile().exists()) {
                // 目标文件所在目录不存在
                if (!destFile.getParentFile().mkdirs()) {
                    // 复制文件失败：创建目标文件所在目录失败
                    Log.e(TAG, "failed to create destFile. path : " +
                            destFile.getAbsolutePath());
                    return false;
                }
            }
        }

        int byteRead = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;
        boolean ret = false;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
            ret = true;
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ret;
        }


    }

    /**
     * 重命名文件
     *
     * @param context 上下文  可以为NULL
     * @param srcPath 源文件地址
     * @param newName 新的文件名称
     * @return 返回操作是否成功
     */
    public static boolean reNameFile(Context context, String srcPath, String newName) {
        File srcFile = new File(srcPath);
        File dstFile = new File(srcFile.getParent() + File.separator + newName);

        if (!srcFile.exists() || !srcFile.isFile()) {
            Log.e(TAG, "renameFile  failed because file not exist or is not a" +
                    "File");
            return false;
        }

        if (dstFile.exists()) {
            Log.e(TAG, "dstFile is exist");
            return false;
        }

        return srcFile.renameTo(dstFile);

    }

//    /**
//     * 文件转成二进制流
//     *
//     * @param srcPath  源文件地址
//     * @param fileByte 将转化后的文件流放入这个byte数组中
//     * @return 返回操作是否成功
//     */
//    public static boolean changeFileToArray(Context context, String srcPath, byte[] fileByte) {
//
//        return true;
//    }

    /**
     *
     * @param context 上下文
     * @param list 存放File类型的list
     * @param fileDirPath 文件夹路径
     * @return
     */
    public static boolean getCurrentDirFiles(Context context,
                                             ArrayList<File> list, String fileDirPath) {

        if (list == null) {
            Log.e(TAG, "list is null");
            return false;
        } else {
            list.clear();
            File dir = new File(fileDirPath);
            if (dir.exists() && !dir.isFile()) {
                File[] files = dir.listFiles();
                list.addAll(Arrays.asList(files));
                return true;
            } else {
                Log.e(TAG, "fileDir is not a dir");
                return false;
            }
        }

    }



    /**
     * 在文件后面追加内容
     *
     * @param srcFilePath 文件地址
     * @param content 追加内容
     */
    public static void appendContentToFile(String srcFilePath, String content) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(srcFilePath, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param srcFilePath 文件地址
     * @param content 替换内容
     */
    public static void overlayContentToFile(String srcFilePath, String content){
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(srcFilePath, false);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean isExits(String filePath) {
        File srcFile = new File(filePath);
        return srcFile.exists();
    }

    public static boolean isFile(String filePath) {
        File srcFile = new File(filePath);
        return srcFile.isFile();
    }


    public static String getContentFromFile(String filePath){

        File srcFile = new File(filePath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(srcFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if(inputStream == null){
            Log.e(TAG, "failed to get fileInputStream, fileInputStream is " +
                    "null. path : " + filePath);
            return null;
        }

        String content = getString(inputStream);

        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content;

    }

    private static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        if(inputStreamReader == null){
            Log.e(TAG, "failed to get InputStreamReader, InputStreamReader is " +
                    "null.");
            return null;
        }

        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder sb = new StringBuilder("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            inputStreamReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
